package com.ang.juc.n7;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        //不安全
//        AccountUnsafe account = new AccountUnsafe(10000);
        //安全
//        AccountSafe account = new AccountSafe(10000);
        //安全
        AccountCas account = new AccountCas(10000);

        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Thread t = new Thread(() -> {
                account.sub();
            });

            t.start();
            ts.add(t);
        }

        for (Thread t : ts) {
            t.join();
        }

        System.out.println("余额："+account.getCount());
    }


}

/**
 * 不安全
 */
@Data
class AccountUnsafe{
    private Integer count;

    public AccountUnsafe(Integer count){
        this.count = count;
    }

    public void sub(){
        this.count = this.count - 10;
    }
}

/**
 * 加锁安全
 */
@Data
class AccountSafe{
    private Integer count;

    public AccountSafe(Integer count){
        this.count = count;
    }

    public synchronized void sub(){
        this.count = this.count - 10;
    }
}

/**
 * CAS安全
 */
@Data
class AccountCas{
    private AtomicInteger count;

    public AccountCas(Integer count){
        this.count = new AtomicInteger(count);
    }

    public  void sub(){
        this.count.getAndAdd(-10);
    }
}
